﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.Skins;

namespace LibExtend
{
    public partial class DetailForm : DevExpress.XtraEditors.XtraForm
    {
        public event LibExtend.Events.DataExchangeHandler DataExchange;

        private int animationTime;
        private int flags;

        public string Number { get; set; }
        public int InnerWidth { get; set; }
        public int InnerHeight { get; set; }

        public Table Item { get; set; }
        DataTable PopupData = new DataTable();
        bool bLock = false;
        
        public DetailForm()
        {
            InitializeComponent();

            if (LibExtend.Config.DetailFormEffect)
            {
                this.Width = 2;
            }
        }

        private void ResetColor()
        {
            Skin currentSkin = CommonSkins.GetSkin(this.LookAndFeel.ActiveLookAndFeel);
            SkinElement element = currentSkin[CommonSkins.SkinLabel];
            Color skinBackColor = element.Color.ForeColor;

            lb50.LinkColor = skinBackColor;
            lb100.LinkColor = skinBackColor;
            lb150.LinkColor = skinBackColor;
            lb200.LinkColor = skinBackColor;
            lb300.LinkColor = skinBackColor;
            lbPrint.LinkColor = skinBackColor;
            lblHistory.LinkColor = skinBackColor;
            lbPrint.LinkColor = skinBackColor;
        }

        public DetailForm(int AnimationTime, int Flags)
        {
            animationTime = AnimationTime;
            flags = Flags;

            InitializeComponent();

            if (LibExtend.Config.DetailFormEffect)
            {
                this.Width = 2;
            }
        }

        private decimal ToDecimal(object value)
        {
            try
            {
                if (object.Equals(value, null) || value is DBNull) return 0;
                return Convert.ToDecimal(value);
            }
            catch
            {
                return 0;
            }
        }

        private string ToString(object value)
        {
            if (object.Equals(value, null) || value is DBNull)
                return "";
            try
            {
                return value.ToString();
            }
            catch { return ""; }
        }

        private void ReloadData(Table table)
        {
            pnlMergeItem.Controls.Clear();
            if (!object.Equals(table, null))
            {
                barDate.EditValue = table.Ngay;
                lbl.Text = table.TenBan;
                txtSubTotal.Text = table.ThanhTien.ToString("n2");
                nuDiscountPercent.Value = table.PT_CK;
                nuPayment.Value = table.KhachTra;
                txtNotes.Text = table.GhiChu;
            }

            txtDiscountValue.Text = table.Tien_CK.ToString("n2");//(nuDiscountPercent.Value * ToDecimal(txtSubTotal.Text) / 100).ToString("n2");
            txtTotal.Text = table.TongTien.ToString("n2");//(ToDecimal(txtSubTotal.Text) - ToDecimal(txtDiscountValue.Text)).ToString("n2");
            if (nuPayment.Value > 0)
                txtReturnValue.Text = (nuPayment.Value - ToDecimal(txtTotal.Text)).ToString("n2");

            grid.DataSource = table.DataSource;
            grid.Focus();
            view.Columns.ColumnByFieldName("DonGia").OptionsColumn.AllowEdit = LibExtend.Config.AllowChangePrice;
            view.Columns.ColumnByFieldName("TongTien").OptionsColumn.AllowEdit = false;

            if (Item.DataMerge != null && Item.DataMerge.Rows.Count > 0)
            {
                pnlMergeItem.Visible = false;
                if (Item.DataMerge.Rows.Count == 1 && ToDecimal(Item.DataMerge.Rows[0]["IdBanHang"]) == Item.IdBanHang)
                    goto tt;
                foreach (DataRow row in Item.DataMerge.Rows)
                {
                    pnlMergeItem.Controls.Add(GetLabel(ToDecimal(row["IdBanHang"]), row["TenBan"].ToString()));
                }

                pnlMergeItem.Controls.Add(GetLabel(
                    "_" + ToDecimal(Item.DataMerge.Rows[0]["IdBanHang"]).ToString(), "Tổng"));
                pnlMergeItem.Visible = true;
            }

        tt:
            ReEnableNew();
        }

        private LinkLabel GetLabel(object Tag, string TblNum)
        {
            LinkLabel _lbl = new LinkLabel();
            _lbl.AutoSize = false;
            _lbl.Width = 50;
            _lbl.Font = new System.Drawing.Font(_lbl.Font.Name, 9F, FontStyle.Bold);
            _lbl.Dock = DockStyle.Left;
            _lbl.TextAlign = ContentAlignment.MiddleCenter;
            _lbl.Click += new EventHandler(_lbl_Click);
            _lbl.MouseUp += new MouseEventHandler(_lbl_MouseUp);
            _lbl.Tag = Tag;
            _lbl.Text = TblNum;
            _lbl.BringToFront();

            return _lbl;
        }

        private void ReEnableNew()
        {
            if (Item.IdBanHang > 0 && Item.KhachTra == 0)
                //Bàn chưa thanh toán không thể tạo mới.
                btNew.Enabled = false;
        }

        void _lbl_MouseUp(object sender, MouseEventArgs e)
        {
            LinkLabel _lbl = (LinkLabel)sender;
            if (ToString(_lbl.Tag).Substring(0, 1) == "_")
                return;

            if (e.Button == System.Windows.Forms.MouseButtons.Right)
                popGroupDetail.ShowPopup(Cursor.Position);
        }

        private void ResetImageAndColor()
        {
            lbl.Image = Item.GetSmallImage();
            //lbl.i
            lbl.ForeColor = Item.GetTextColor();
        }

        private void Form2_Load(object sender, EventArgs e)
        {
            this.Height = InnerHeight;
            this.Width = InnerWidth;

            ReloadData(Item);
            ResetImageAndColor();

            if (this.DataExchange != null)
            {
                LibExtend.Events.Sender _sender = new LibExtend.Events.Sender(LibExtend.Events.ObjectName.Catalog, LibExtend.Events.ActionType.Get);
                this.DataExchange(_sender);
                if (!object.Equals(_sender.ObjectValue, null))
                {
                    PopupData = (DataTable)_sender.ObjectValue;
                    repPro.SetDataSource(PopupData, "MaHang,TenHang#Mã,Tên");
                }

                _sender = new LibExtend.Events.Sender(LibExtend.Events.ObjectName.Units, LibExtend.Events.ActionType.Get);
                this.DataExchange(_sender);
                if (!object.Equals(_sender.ObjectValue, null))
                {
                    repUnit.SetDataSource((DataTable)_sender.ObjectValue, "TenDVT#Tên");
                }
            }

            ResetColor();
        }

        void _lbl_Click(object sender, EventArgs e)
        {
            LinkLabel lbl = (LinkLabel)sender;

            barUnGroup.Enabled = (this.Item.KhachTra > 0) ? false : true;
            if (DataExchange != null)
            {
                LibExtend.Events.Sender _sender = new LibExtend.Events.Sender(LibExtend.Events.ObjectName.MergeItem, LibExtend.Events.ActionType.Clicked);
                bLock = false;
                if (ToString(lbl.Tag).Substring(0, 1) == "_")
                {
                    _sender = new LibExtend.Events.Sender(LibExtend.Events.ObjectName.SummaryMerge, LibExtend.Events.ActionType.Clicked);
                    bLock = true;
                }

                Table tbl = new Table();
                tbl.IdBanHang = (int)ToDecimal(ToString(lbl.Tag).Replace("_", ""));
                _sender.Item = tbl;
                DataExchange(_sender);

                if (!_sender.Cancel)
                {
                    _sender.Item.TenBan = lbl.Text;
                    Item = _sender.Item;
                    ReloadData(Item);
                }

                ResetLock();
            }
        }

        private void ResetLock()
        {
            view.OptionsBehavior.ReadOnly = bLock;
            nuDiscountPercent.Properties.ReadOnly = bLock;
            txtNotes.Properties.ReadOnly = bLock;
            btDel.Enabled = !bLock;
        }

        private void Form2_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void Form2_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                //if (btUp.Enabled)
                //    btnSave_Click(btnSave, new EventArgs());
            }
            catch (Exception ex)
            {
                e.Cancel = true;
                MessageBox.Show(ex.Message, "Error.", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            WinAPI.AnimateWindow(this.Handle, 500, WinAPI.AW_HIDE | WinAPI.AW_CENTER);
        }

        private void BaseDetail_FormClosed(object sender, FormClosedEventArgs e)
        {

        }

        private void view_TableValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.Column.FieldName.ToLower() == "dongia" || e.Column.FieldName.ToLower() == "soluong" ||
                e.Column.FieldName.ToLower() == "pt_ck")
            {
                DataRow row = view.GetFocusedDataRow();
                if (!object.Equals(row, null))
                    CalcRow(row);
            }
            else if (e.Column.FieldName.ToLower() == "idhanghoa")
            {
                DataRow row = view.GetFocusedDataRow();
                if (!object.Equals(row, null))
                {
                    if (IsExists(Convert.ToInt32(row["IdHangHoa"])))
                    {
                        MessageBox.Show("Thực đơn này đã tồn tại, vui lòng chọn thực đơn khác.", "Thông báo.",
                            MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    DataRow[] rS = PopupData.Select("IdHangHoa =" + row["IdHangHoa"].ToString());
                    if (!object.Equals(rS, null) && rS.Length > 0)
                    {
                        row["TenHang"] = rS[0]["TenHang"];
                        //row["TenDVT"] = rS[0]["TenDVT"];
                        row["IdDVT"] = rS[0]["IdDVT"];
                        row["SoLuong"] = 1;
                        row["DonGia"] = rS[0]["DonGia"];
                        view.UpdateCurrentRow();
                        CalcRow(row);

                        btUp_ItemClick(btUp, null);
                    }
                }
            }

            EnableSave();
        }

        private void CalcRow(DataRow row)
        {
            row["ThanhTien"] = ToDecimal(row["SoLuong"]) * ToDecimal(row["DonGia"]);
            row["Tien_CK"] = ToDecimal(row["ThanhTien"]) * ToDecimal(row["PT_CK"]) / 100;
            row["TongTien"] = ToDecimal(row["ThanhTien"]) - ToDecimal(row["Tien_CK"]);
            view.PostEditor();
            
            SumTotal();
        }

        private void SumTotal()
        {
            DataTable Detail = (DataTable)grid.DataSource;
            if (Detail != null) Detail.AcceptChanges();

            if (Detail != null && Detail.Rows.Count > 0)
            {
                decimal sub = 0;
                foreach (DataRow row in Detail.Rows)
                    sub += ToDecimal(row["TongTien"]);
                txtSubTotal.Text = sub.ToString("n2");
                txtDiscountValue.Text = (sub * nuDiscountPercent.Value / 100).ToString("n2");
                txtTotal.Text = (sub - ToDecimal(txtDiscountValue.Text)).ToString("n2");
            }
        }

        private void nuDiscountPercent_ValueChanged(object sender, EventArgs e)
        {
            if (txtSubTotal.Text == "") txtDiscountValue.Text = "";
            else
            {
                txtDiscountValue.Text = (ToDecimal(txtSubTotal.Text) * nuDiscountPercent.Value / 100).ToString("n2");
                txtTotal.Text = (ToDecimal(txtSubTotal.Text) - ToDecimal(txtDiscountValue.Text)).ToString("n2");
            }
            EnableSave();

            nuPayment_Validated(nuPayment, e);
        }

        private void EnableSave()
        {
            if(Item.KhachTra <= 0)
                btUp.Enabled = true;
        }

        private void nuPayment_ValueChanged(object sender, EventArgs e)
        {
            EnableSave();
        }

        private void grid_DragOver(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(typeof(DataRow)))
                e.Effect = DragDropEffects.Move;
            else
                e.Effect = DragDropEffects.None;
        }

        private bool IsExists(int ProductID)
        {
            DataTable table = grid.DataSource as DataTable;
            DataRow[] rS = table.Select("IdHangHoa=" + ProductID);
            if (!object.Equals(rS, null) && rS.Length > 0) return true;
            return false;
        }

        private void grid_DragDrop(object sender, DragEventArgs e)
        {
            AddItem(e.Data.GetData(typeof(DataRow)) as DataRow);
        }

        public void AddItem(DataRow ro)
        {
            DataTable table = grid.DataSource as DataTable;

            if (ro != null && table != null && ro.Table != table)
            {
                //Important ! Copy data to not synchronized price to menu control
                DataTable tmp = table.Clone();
                tmp.ImportRow(ro);

                DataRow row = tmp.Rows[0];
                //End copy

                DataRow[] rS = table.Select("IdHangHoa=" + Convert.ToInt32(row["IdHangHoa"]));
                if (!object.Equals(rS, null) && rS.Length > 0)
                {
                    rS[0]["SoLuong"] = ToDecimal(rS[0]["SoLuong"]) + 1;
                }
                else
                {
                    if (this.DataExchange != null)
                    {
                        this.Item.Ngay = Convert.ToDateTime(barDate.EditValue);
                        LibExtend.Events.Sender send = new LibExtend.Events.Sender(LibExtend.Events.ObjectName.Price, LibExtend.Events.ActionType.Get, this.Item);
                        send.ObjectValue = Convert.ToInt32(row["IdHangHoa"]);

                        this.DataExchange(send);
                        if (!send.Cancel && Convert.ToDecimal(send.ObjectValue) > 0)
                        {
                            row["DonGia"] = Convert.ToDecimal(send.ObjectValue);
                        }
                    }
                    
                    table.ImportRow(row);
                }

                CalcRow(table.Select("IdHangHoa=" + Convert.ToInt32(row["IdHangHoa"]))[0]);

                btUp_ItemClick(btUp, null);
            }
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == Keys.Escape)
                this.Close();
            return base.ProcessCmdKey(ref msg, keyData);
        }

        private void view_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {
            EnableSave();
        }

        private void barUnGroup_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (this.DataExchange != null)
            {
                LibExtend.Events.Sender send = new LibExtend.Events.Sender(LibExtend.Events.ObjectName.None, LibExtend.Events.ActionType.UnGroup, this.Item);
                this.DataExchange(send);
                if (!send.Cancel)
                {
                    ReloadData(this.Item);
                }
            }
        }

        private void btNew_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (this.DataExchange != null)
            {
                LibExtend.Events.Sender send = new LibExtend.Events.Sender(LibExtend.Events.ObjectName.New, LibExtend.Events.ActionType.Clicked, this.Item);
                this.DataExchange(send);
                if (send.Cancel)
                    return;
            }

            barDate.EditValue = DateTime.Now;

            Item.KhachTra = 0;
            Item.PT_CK = 0;
            Item.IdBanHang = 0;
            Item.GhiChu = "";
            txtSubTotal.Text = "0";
            nuDiscountPercent.Value = 0;
            txtDiscountValue.Text = "0";
            txtTotal.Text = "0";
            txtReturnValue.Text = "0";
            nuPayment.Value = 0;
            grid.DataSource = Item.DataSource.Clone();
            Item.DataSource = Item.DataSource.Clone();
            Item.ThanhTien = 0;
            Item.iState = Table.State.None;

            pnlMergeItem.Controls.Clear();
        }

        private void btUp_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (ToDecimal(nuPayment.EditValue) > 0 && ToDecimal(nuPayment.EditValue) < ToDecimal(txtTotal.Text))
            {
                MessageBox.Show("Số tiền khách thanh toán không thể nhỏ hơn tổng số tiền cần thanh toán.", "Thông báo.",
                    MessageBoxButtons.OK, MessageBoxIcon.Error); 
                return;
            }

            if (bLock)// Is summary
            {
                LibExtend.Events.Sender send = new LibExtend.Events.Sender(LibExtend.Events.ObjectName.UpdateSummary, LibExtend.Events.ActionType.Clicked, this.Item);
                this.DataExchange(send);
                if (send.Cancel)
                    btUp.Enabled = true;
                return;
            }

            view.PostEditor();
            view.UpdateCurrentRow();

            Item.Ngay = Convert.ToDateTime(barDate.EditValue);
            Item.ThanhTien = ToDecimal(txtSubTotal.Text);
            Item.PT_CK = nuDiscountPercent.Value;
            Item.Tien_CK = ToDecimal(txtDiscountValue.Text);
            Item.KhachTra = nuPayment.Value;
            Item.TongTien = ToDecimal(txtTotal.Text);
            Item.GhiChu = txtNotes.Text;

            DataTable DT = (DataTable)grid.DataSource;
            if (DT != null) DT.AcceptChanges();

            Item.DataSource = DT;

            if (this.DataExchange != null)
            {
                LibExtend.Events.Sender send = new LibExtend.Events.Sender(LibExtend.Events.ObjectName.Update, LibExtend.Events.ActionType.Clicked, this.Item);
                this.DataExchange(send);
                if (!send.Cancel)
                {
                    btUp.Enabled = false;
                    ReEnableNew();
                }
            }
        }

        private void btPrint_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (this.DataExchange != null)
            {
                LibExtend.Events.Sender send = new LibExtend.Events.Sender(LibExtend.Events.ObjectName.Print, LibExtend.Events.ActionType.Clicked, this.Item);
                this.DataExchange(send);
            }
        }

        private void btDel_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (this.DataExchange != null)
            {
                LibExtend.Events.Sender send = new LibExtend.Events.Sender(LibExtend.Events.ObjectName.Delete, LibExtend.Events.ActionType.Clicked, this.Item);
                this.DataExchange(send);
                if (!send.Cancel)
                {
                    btNew_ItemClick(null, null);
                }
            }
        }

        private void btBack_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            this.Close();
        }

        private void grid_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                view.DeleteSelectedRows();
                SumTotal();
                if (MessageBox.Show("Bạn có chắc chắc muốn xóa dòng dữ liệu này không?", "Xác nhận", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) ==
                    System.Windows.Forms.DialogResult.No)
                    return;

                btUp_ItemClick(btUp, null);
            }
        }

        private void txtNotes_TextChanged(object sender, EventArgs e)
        {
            btUp.Enabled = true;
        }

        private void barDate_EditValueChanged(object sender, EventArgs e)
        {
            btUp.Enabled = true;
        }

        private void nuDiscountPercent_EditValueChanged(object sender, EventArgs e)
        {
            btUp.Enabled = true;
        }

        private void nuPayment_Validated(object sender, EventArgs e)
        {
            //nuPayment_ValueChanged(nuPayment, e);
            txtReturnValue.Text = (ToDecimal(nuPayment.EditValue) - ToDecimal(txtTotal.Text)).ToString("N");

            //if (ToDecimal(txtReturnValue.Text) >= 0)
                btUp_ItemClick(btUp, null);
        }

        private void lb500_Click(object sender, EventArgs e)
        {
            nuPayment.EditValue = ToDecimal(((LinkLabel)sender).Text) * 1000;
            nuPayment_Validated(nuPayment, e);
        }

        private void btPrinter_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            string PrinterName = "";
            using (PrintDialog printDialog = new PrintDialog())
            {
                printDialog.Document = new System.Drawing.Printing.PrintDocument();
                if (printDialog.ShowDialog() == DialogResult.OK)
                {
                    PrinterName = printDialog.PrinterSettings.PrinterName;
                }
            }

            Config.PrinterName = PrinterName;

            if (this.DataExchange != null)
            {
                LibExtend.Events.Sender send = new LibExtend.Events.Sender(LibExtend.Events.ObjectName.Print, LibExtend.Events.ActionType.Changed, null);
                this.DataExchange(send);
            }
        }

        private void lblHistory_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            popHistory.ClearLinks();
            if (this.DataExchange != null)
            {
                this.Item.Ngay = Convert.ToDateTime(barDate.EditValue);
                LibExtend.Events.Sender send = new LibExtend.Events.Sender(LibExtend.Events.ObjectName.History, LibExtend.Events.ActionType.Get, this.Item);
                this.DataExchange(send);
                if (!send.Cancel)
                {
                    if (!object.Equals(send.ObjectValue, null))
                    {
                        DataTable _dt = (DataTable)send.ObjectValue;
                        if (_dt != null && _dt.Rows.Count > 0)
                        {
                            foreach (DataRow ro in _dt.Rows)
                            {
                                DevExpress.XtraBars.BarButtonItem _item = new DevExpress.XtraBars.BarButtonItem();
                                _item.Caption = ro["Gio"].ToString() + "      " + Convert.ToDecimal(ro["TongTien"]).ToString("N");
                                _item.Id = Convert.ToInt32(ro["IdBanHang"]);
                                _item.Name = "menu" + Convert.ToInt32(ro["IdBanHang"]).ToString();
                                _item.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(_item_ItemClick);
                                popHistory.ItemLinks.Add(_item);
                            }
                        }
                    }
                }
            }
            popHistory.ShowPopup(barMngDetail, PointToScreen(lblHistory.Location));
        }

        void _item_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (this.DataExchange != null)
            {
                LibExtend.Events.Sender send = new LibExtend.Events.Sender(LibExtend.Events.ObjectName.Review, LibExtend.Events.ActionType.Get, this.Item);
                send.ObjectValue = e.Item.Id;
                this.DataExchange(send);
                if (!send.Cancel)
                {
                    ReloadData(send.Item);
                }
            }
        }

        private void lbl_Click(object sender, EventArgs e)
        {
            //Show current table info
            if (this.DataExchange != null)
            {
                LibExtend.Events.Sender send = new LibExtend.Events.Sender(LibExtend.Events.ObjectName.Current, LibExtend.Events.ActionType.Get, this.Item);
                this.DataExchange(send);
                if (!send.Cancel)
                {
                    ReloadData(send.Item);
                }
            }
        }

        private void lbPrint_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (this.DataExchange != null)
            {
                LibExtend.Events.Sender send = new LibExtend.Events.Sender(LibExtend.Events.ObjectName.PrintMix, LibExtend.Events.ActionType.Clicked, this.Item);
                this.DataExchange(send);
            }
        }

    }
}
